package com.wlient.basic.Thread.safeThread;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class SafeLock {

    private static ReentrantReadWriteLock  reentrantLock = new ReentrantReadWriteLock ();
    private static ReentrantReadWriteLock.ReadLock readLock = reentrantLock.readLock();//读锁,共享锁
    private static ReentrantReadWriteLock.WriteLock writeLock = reentrantLock.writeLock();//写锁，排它锁
    public static void main(String[] args) {
        SafeLockThread safeLockThread = new SafeLockThread();
        Thread t1 = new Thread(safeLockThread);
        Thread t2 = new Thread(safeLockThread);
        Thread t3 = new Thread(safeLockThread);

        t1.start();
        t2.start();
        t3.start();
    }
}

class SafeLockThread implements Runnable{
    private int tickets = 100;
    private static ReentrantReadWriteLock  reentrantLock = new ReentrantReadWriteLock ();
    private static ReentrantReadWriteLock.ReadLock readLock = reentrantLock.readLock();//读锁,共享锁
    private static ReentrantReadWriteLock.WriteLock writeLock = reentrantLock.writeLock();//写锁，排它锁

    @Override
    public void run() {
        while (tickets>0) {
            try {
                //在这里锁住，有点类似同步监视器
                writeLock.lock();
                if (tickets > 0) {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + ":\t票号:" + tickets + "\t剩余票数:" + --tickets);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //操作完成共享数据后在这里解锁
                writeLock.unlock();
            }
        }
    }
}
